package com.bianmaba.oauth.configuration;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.client.DefaultOAuth2ClientContext;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
import org.springframework.security.oauth2.client.token.AccessTokenRequest;
import org.springframework.security.oauth2.client.token.DefaultAccessTokenRequest;
import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsAccessTokenProvider;
import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails;

/**
 * @program: spring-oauth2-demo
 * @description:
 * @author: Chenjiabin
 * @create: 2018/11/8 14:01
 **/
@Configuration
public class ClientAutoConfiguration {
    @Bean("orderResourceDetails")
    @ConfigurationProperties(prefix = "order.client")
    public OAuth2ProtectedResourceDetails resourceDetails() {
        return new ClientCredentialsResourceDetails();
    }

    @Bean("orderOAuth2RestTemplate")
    @Qualifier(value = "orderResourceDetails")
    public OAuth2RestTemplate orderOAuth2RestTemplate() {
        AccessTokenRequest accessTokenRequest = new DefaultAccessTokenRequest();
        ClientCredentialsAccessTokenProvider provider = new ClientCredentialsAccessTokenProvider();

        OAuth2RestTemplate template = new OAuth2RestTemplate(resourceDetails(), new DefaultOAuth2ClientContext(accessTokenRequest));
        template.setAccessTokenProvider(provider);
        return template;
    }
}
